import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  CircularProgress,
  Divider,
  Stack,
} from '@mui/material';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import axios from 'axios';
import { API_BASE_URL } from '../config';
function Dashboard() {
  const [blocks, setBlocks] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    fetchBlocks();
  }, []);

  const fetchBlocks = async () => {
    try {
      const response = await axios.get(`${API_BASE_URL}/chain`);
      setBlocks(response.data.chain);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching blocks:', error);
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="60vh">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        区块链链表结构
      </Typography>
      <Stack direction="row" spacing={2} alignItems="center" flexWrap="wrap">
        {blocks.map((block, idx) => (
          <React.Fragment key={block.index}>
            <Card
              sx={{
                minWidth: 260,
                cursor: 'pointer',
                border: '2px solid #2196f3',
                background: '#1a2236',
                '&:hover': { boxShadow: 6 },
              }}
              onClick={() => navigate(`/block/${block.index}`)}
            >
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  区块 #{block.index}
                </Typography>
                <Typography color="textSecondary" gutterBottom noWrap>
                  哈希: {block.hash.slice(0, 12)}...<br />
                  前哈希: {block.previous_hash.slice(0, 12)}...
                </Typography>
                <Typography variant="body2" color="textSecondary">
                  交易数: {block.transactions.length}
                </Typography>
                <Typography variant="caption" color="textSecondary">
                  时间: {new Date(block.timestamp).toLocaleString()}
                </Typography>
              </CardContent>
            </Card>
            {idx !== blocks.length - 1 && (
              <ArrowForwardIcon sx={{ fontSize: 40, color: '#2196f3' }} />
            )}
          </React.Fragment>
        ))}
      </Stack>
    </Box>
  );
}

export default Dashboard; 